<script setup>
import {onMounted, resolveDirective} from 'vue'
import {NAvatar, NButton, NCheckbox, NFlex, NInput, NInputNumber, NSelect, NTag, NUpload, useMessage} from 'naive-ui'
import api from '@/api'
import default_image from "@/assets/images/mz.jpg"
import Info from "@/views/customer/user/info.vue";
import {getToken} from "@/utils";

const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE
const message = useMessage()

const data = reactive({
  active:false,
  value: 0,
  customers:[],
  search_customer:'',
  goods:[],
  consumables:[],
  e_sign:'',
  other_form:[],
  before_pic:[],
  after_pic:[],
  search_goods:'',
  search_consumables:'',
  uploadAction: base_path+'api/appointment/project/file',
  token: getToken(),
  select_customer:{
    id:0,
    name:"暂未选择",
    phone:"x",
    money_deposit:0
  },
  select_skus:[],
  select_ids:[],
  select_price:0,
  select_goods:[],
  select_goods_nums:[],
  yue:0,
  designers:[],
  select_designers:[],
  select_space:1,
  desc:"",
  show_info:false,
  todo_data:[],
  drawer_title:''
});

onMounted(() => {
  api.getSpaceList().then((res) => (data.option_space = res.data))
  get_customers()
  get_designers()
  get_consumables()
})
function select_customer(item){
  data.select_customer = item
  data.select_skus = []//选中的商品规则和数量
  message.success('已选择客户:'+item.name)
  get_goods()
  show_info(item)
}

function select_kx_projects(item){
  let select_count = 0
  data.todo_data['zx_include'].forEach(item =>{
    if (item.is_select === true) select_count++
  })
  if (select_count < data.todo_data['zx_can_do'] || item.is_select===true){
    item.is_select = !item.is_select
  }else {
    message.info("超过可选数量")
  }
}

function get_customers(){
  api.getSaasUserList({
    name:data.search_customer
  }).then((res) => (data.customers = res.data))
}
function get_designers(){
  api.getSettingDesigner().then((res) => (data.designers = res.data))
}
function get_goods(){
  api.getSaasBucklingList({
    name:data.search_goods,
    user_id:data.select_customer.id,
    page:1,
    page_size:1000
  }).then((res) => (data.goods = res.data))
}
function get_consumables(){
  api.getConsumables({
    name:data.search_consumables,
  }).then((res) => (data.consumables = res.data))
}

function show_info(item){
  data.show_info = true
  data.select_customer.id = item.id
}
function handleChange(value, index,i,b){
  data.select_skus = []//选中的商品规则和数量
  data.goods[index]['groups'][i]['buckling_item'][b].select_nums = value;
  data.goods.map(item1 => {
    console.log(item1)
    item1.groups.map(item2 => {
      item2.buckling_item.map(
          item => {
            if(item.select_nums>0){
              let group_id = item2.group_id
              message.success('已选择'+group_id+':'+item.sku_name)
              data.select_skus.push(
                  {
                    "id":item.id,
                    "buckling_id":item.id,
                    "sku_name":item.sku_name,
                    "nums":item.select_nums,
                    "goods_name":item.good_name,
                    "group_id":group_id?group_id:0,
                  }
              )

            }

          }
      )

    })
  })
  console.log(data.select_skus)


  // let count = 0
  // if(data.goods[index]['groups'][i]['type']===2){
  //   data.goods[index]['groups'][i]['buckling_item'].map(item => {
  //     if(item.select_nums>0){
  //       count+=item.select_nums
  //     }
  //   })
  //
  // }
  // if (count>data.goods[index]['groups'][i]['times']){
  //   message.success('超过合计使用次数')
  //   data.goods[index]['groups'][i]['buckling_item'][b].select_nums = value-1;
  //   return
  // }
  // data.goods[index]['groups'][i]['buckling_item'][b].select_nums = value;
  // data.goods[index]['groups'][i]['buckling_item'].map(item => {
  //   if(item.select_nums>0){
  //     // message.success('已选择:'+item.sku_name)
  //     let group_id = data.goods[index]['groups'][i].group_id
  //     data.select_skus.push(
  //         {
  //           "id":item.id,
  //           "buckling_id":item.id,
  //           "sku_name":item.sku_name,
  //           "nums":item.select_nums,
  //           "goods_name":item.good_name,
  //           "group_id":group_id?group_id:0,
  //         }
  //     )
  //     console.log(data.select_skus)
  //   }
  // })
}
function consumablesChange(value, index){
  data.select_consumables = []
  data.consumables[index].select_nums = value;
  data.consumables.map(item => {
    if(item.select_nums>0){
      // message.success('已选择商品:'+item.goods_name)
      data.select_consumables.push(
          {
            "id":item.id,
            "nums":item.select_nums,
            "name":item.name,
          }
      )
    }
  })
}


function on_save(){
  if(!data.select_customer.id){
    message.error('请先选择客户')
    return
  }

  console.log(data.select_skus)
  if(data.select_skus.length===0){
    message.error('请先选择划扣项目')
    return
  }
  api.createCases({
    add_uid:0,
    user_id:data.select_customer.id,
    space_id:data.select_space,
    desc:data.desc,
    designer_ids:data.select_designers,
    buckling_data:data.select_skus,
    buckling_consumables:data.select_consumables,
    e_sign:data.e_sign,
    other_form:data.other_form,
    before_pic:data.before_pic,
    after_pic:data.after_pic,

  }).then((res) => {
    message.success(res.msg)
    get_goods()
    get_consumables()
  })

}

function use_card(){
  data.select_ids = []
  if(!data.select_customer.id){
    message.error('请先选择客户')
    return
  }

  if(data.todo_data['zx_include']){
    data.todo_data['zx_include'].map(item => {
      if(item.is_select){
        data.select_ids.push(item.id)
      }
    })
  }
  if(data.todo_data['bd_include']){
    data.todo_data['bd_include'].map(item => {
      if(item.is_select){
        data.select_ids.push(item.id)
      }
    })
  }

  if(data.select_ids.length===0){
    message.error('请先选择开卡项目')
    return
  }
  api.startUse({
    id:data.select_todo_id,
    selected_ids:data.select_ids,
    add_uid:0,
  }).then((res) => {
    message.success(res.msg)
    data.select_todo_id = ''
    get_goods()
    get_consumables()
  })

}
const activate = (todo) => {
  data.active = true;
  data.drawer_title = todo.goods_name
  data.select_todo_id = todo.id,
      api.getSaasGetGroup({
        data_id:todo.id,
      }).then((res) => {
        data.todo_data = res.data
        if(data.todo_data['zx_include']){
          data.todo_data['zx_include'] = data.todo_data['zx_include'].map(item => ({
            ...item,
            is_select: false
          }))
        }

        data.todo_data['bd_include'] = data.todo_data['bd_include'].map(item => ({
          ...item,
          is_select: true
        }))
        console.log(data.todo_data['bd_include'])
      })
};

const handleFinish = ({ file, event }) => {
  let data = (event?.target).response
  data = JSON.parse(data)
  if (data.code === 200) {
    file.url = data.data.url
    message.success('上传成功')
  } else {
    message.error(data.data)
  }

  return file
}

const customRequestMethod1 = (options) => {
  console.log(options, 'options');

  const { file } = options.file;
  const formData = new FormData();
  formData.append('file', file);
  fetch(data.uploadAction, {
    method: 'POST',
    headers: options.headers,
    body: formData,
  })
      .then((response) => response.json())
      .then((ret) => {
        if (ret.code === 200) {
          data.e_sign = ret.data.url
          message.success('签名上传成功');
          options.onProgress(ret);
        } else {
          message.error(ret.msg);
        }
      })
}


</script>

<template>
  <AppPage :show-footer="false" style="padding-top: 60px;">
    <n-card  style="height: calc(100vh - 100px);" content-style="padding: 0px;"    size="small" :segmented="{
          content: true,
          footer: 'soft',
        }">
      <n-tabs type="line" animated size="large" :tabs-padding="20" pane-style="padding: 20px;">
        <n-tab-pane name="选择划扣">
          <n-grid :cols="3" :x-gap="12" :y-gap="8">
            <n-gi  :span="1">
              <n-card style="height: calc(100vh - 200px);"  content-style="padding: 0px;"   title="客户选择" size="small" :segmented="{
                    content: true,
                    footer: 'soft',
                  }" >
                <div style="margin:20px">
                  <NInput v-model:value="data.search_customer" size="large" clearable type="text" placeholder="请输入姓名/手机号"
                          @keyup="get_customers()" />
                </div>
                <n-scrollbar style="max-height: calc(100vh - 350px);padding:0 20px 20px 20px">
                  <n-card embedded  v-for="item in data.customers" class="customer_card" hover:card-shadow   size="small" :segmented="{
                              content: true,
                              footer: 'soft',
                            }"
                          @click="select_customer(item)"
                  >
                    <template #header>
                      <div style="display: flex; align-items: center;">
                        <NAvatar :src="item.avatar" :fallbackSrc="default_image" style="width: 30px; height: 30px; margin-right: 10px;border-radius: 50%" />
                        <span>{{ item.name }}</span>
                      </div>
                    </template>
                    <template #header-extra>
                      <NTag type="error" v-if="item===data.select_customer">已选择</NTag>&nbsp;
                      <NTag >{{item.role_name}}</NTag>

                    </template>
                    <template #footer>
                      <span color="#ef504e"></span>
                      <n-flex justify="space-between" size="large">
                        <div>卡号: <span>{{item.card_no}}</span> </div>
                        <div>电话: <span>{{item.phone}}</span></div>
                      </n-flex>
                    </template>
                  </n-card>
                </n-scrollbar>
              </n-card>
            </n-gi>
            <n-gi  :span="2">
              <n-card style="height: calc(100vh - 200px);" content-style="padding: 0px;"   title="疗程项目选择" size="small" :segmented="{
                    content: true,
                    footer: 'soft',
                  }">
                <div style="margin:20px">
                  <NInput v-model:value="data.search_goods" size="large" clearable type="text" placeholder="请输入商品名称"
                          @keyup="get_goods()" />
                </div>
                <n-scrollbar v-if="data.goods.length>0" style="max-height: calc(100vh - 350px);padding:0 20px 20px 20px">
                  <n-card embedded v-for="(item,index) in data.goods" class="customer_card" hover:card-shadow  size="small" :segmented="{
                              content: true,
                              footer: 'soft',
                            }">
                    <template #header-extra>
                      <n-button v-if="item.status===0" type="primary"  @click="activate(item)">去开卡</n-button>
                      <n-button v-if="item.status===1" type="primary" dashed disabled>已开卡</n-button>
                      <n-button v-if="item.status===2" type="error" dashed disabled>已用完</n-button>
                    </template>
                    <template #header>
                      <div style="display: flex; align-items: center;">
                        <NAvatar :src="item.goods_cover" :fallbackSrc="default_image" style="width: 40px; height: 40px; margin-right: 10px;" />
                        <div style="height:40px;line-height:20px">{{ item.goods_name }}<br><span style="font-size: 12px;color:#747586">{{ item.created_at }}</span></div>
                      </div>
                    </template>
                    <!--              项目划扣选择-->
                    <template v-if="item.type===1 && item.status===1" #footer>
                      <div >
                        <div v-for="(group,i) in item['groups']">
                          <n-flex  justify="space-between" size="large">
                            <div>规格: <span>{{item.sku_name}}(共{{group['buckling_item'][0].last_nums}}次)</span> </div>
                          </n-flex>
                          <n-flex v-for="(buck,b) in group['buckling_item']"  justify="space-between" size="large">
                            <span>{{buck['good_name']}}{{buck['sku_name']}}</span>
                            <span> <n-input-number style="width: 100px" :min="0" :max="buck.last_nums" v-model:value=buck.select_nums @update:value="(value) => handleChange(value,index,i,b)" /></span>
                          </n-flex>
                        </div>
                      </div>
                    </template>
                    <!--              商品划扣选择-->
                    <n-collapse v-if="item.type===2 && item.status===1" justify="space-between" size="large" >
                      <n-collapse-item :title="group['group_name']" v-for="(group,i) in item['groups']">
                        <template #header-extra>
                          <div v-if="group['group_name']">
                            <!--                        <span v-if="group['group_type']===1">单次可用{{group.times}}次</span>-->
                            <span v-if="group['group_type']===2">合计可用{{group.times}}次</span>
                            <span v-if="group['group_type']===3">时段{{group.times}}次</span>
                          </div>
                        </template>
                        <n-flex v-for="(buck,b) in group['buckling_item']"  justify="space-between" size="large" style="margin-bottom: 8px">
                          <span>{{buck['good_name']}}({{buck['sku_name']}})<span v-if="group['group_type']===1">(剩余{{buck['last_nums']}}次)</span></span>
                          <span> <n-input-number style="width: 100px" :min="0" :max="group['group_type']===2?group.times:buck['last_nums']" v-model:value=buck.select_nums @update:value="(value) => handleChange(value,index,i,b)" /></span>
                        </n-flex>
                      </n-collapse-item>
                    </n-collapse>
                  </n-card>
                </n-scrollbar>
                <n-empty description="该客户暂无疗程卡" v-else style="margin-top: 50px"></n-empty>
              </n-card>
            </n-gi>
          </n-grid>
        </n-tab-pane>
        <n-tab-pane name="资料填写">
          <n-grid :cols="3" :x-gap="12" :y-gap="8">
            <n-gi :span="1">
              <n-card style="height: calc(100vh - 200px);" content-style="padding: 0px;"   title="技师/耗材" size="small" :segmented="{
                    content: true,
                    footer: 'soft',
                  }">
                <div style="height: calc(50vh - 100px)">
                  <n-tag :bordered="false">
                    耗材消耗
                  </n-tag>
                  <div style="margin:20px">
                    <NInput v-model:value="data.search_consumables" size="large" clearable type="text" placeholder="请输入耗材名称"
                            @keyup="get_consumables()" />
                  </div>
                  <n-scrollbar v-if="data.consumables.length>0" style="max-height: calc(100vh - 550px);padding:0  10px 20px 10px">
                    <n-card  embedded v-for="(item,index) in data.consumables" class="customer_card" hover:card-shadow  size="small" :segmented="{
                                content: true,
                                footer: 'soft',
                              }">
                      <template #header>
                        <div style="display: flex; align-items: center;">
                          <!--                    <NAvatar :src="item.goods_cover" :fallbackSrc="default_image" style="width: 40px; height: 40px; margin-right: 10px;" />-->
                          <div style="height:20px;">{{ item.name }}</div>
                        </div>
                      </template>
                      <template #header-extra>
                        <div> <n-input-number style="width: 100px" :min="0"  @update:value="(value) => consumablesChange(value, index)" /></div>
                        &nbsp&nbsp{{item.danwei}}
                      </template>
                    </n-card>
                  </n-scrollbar>
                  <n-empty description="暂无耗材" v-else style="margin-top: 50px"></n-empty>
                </div>

                <div style="height: 50vh">
                  <n-tag :bordered="false">
                    技师选择
                  </n-tag>
                  <!--            <div style="margin:20px">-->
                  <!--              <NInput v-model:value="data.search_consumables" size="large" clearable type="text" placeholder="请输入耗材名称"-->
                  <!--                      @keyup="get_consumables()" />-->
                  <!--            </div>-->
                  <n-scrollbar v-if="data.consumables.length>0" style="max-height:250px;padding:20px 20px 20px 20px">
                    <n-checkbox-group v-model:value="data.select_designers">
                      <n-card embedded  v-for="item in data.designers" class="customer_card" hover:card-shadow  size="small" :segmented="{
                               content: true,
                               footer: 'soft',
                             }">
                        <template #footer>
                          <n-flex justify="space-between" size="small" style="width:100%;margin-bottom:5px">
                            <div><n-checkbox size="large" :label="item.name" :value="item.id"/> </div>
                          </n-flex>
                        </template>
                      </n-card>
                    </n-checkbox-group>
                  </n-scrollbar>
                  <n-empty description="暂无技师" v-else style="margin-top: 50px"></n-empty>
                </div>

              </n-card>
            </n-gi>
            <n-gi :span="2">
              <n-card style="height: calc(100vh - 200px);" content-style="padding: 20px;"   title="其它" size="small" :segmented="{
                    content: true,
                    footer: 'soft',
                  }">
                <n-alert :title="'客户:'+data.select_customer.name+'('+data.select_customer.phone+')'" type="success">
                  <div v-for="item in data.select_skus">{{item.good_name}}({{item.sku_name}})x{{item.nums}} </div>
                </n-alert>
                <NFlex>
                  <div class="other_card">
                    <label>电子签名</label>
                    <NUpload :action="data.uploadAction" :headers="{ token: data.token }" :max="1"
                             :show-file-list=true :custom-request="customRequestMethod1" list-type="image-card"></NUpload>
                  </div>

                </NFlex>
                <NFlex>
                  <div class="other_card">
                    <label>术前对比图</label>
                    <NUpload :action="data.uploadAction" :headers="{ token: data.token }" multiple
                             list-type="image-card" @finish="handleFinish" v-model:file-list="data.before_pic">
                    </NUpload>
                  </div>
                  <div class="other_card">
                    <label>术后对比图</label>
                    <NUpload :action="data.uploadAction" :headers="{ token: data.token }" multiple list-type="image-card"
                             @finish="handleFinish" v-model:file-list="data.after_pic">
                    </NUpload>
                  </div>
                </NFlex>

                <NSelect

                    style="width: 100%;margin-bottom:10px;margin-top: 10px"
                    :options="data.option_space"
                    clearable
                    placeholder="请选结算门店"
                    v-model:value="data.select_space"
                />
                <n-input button-placement="both" style="width: 100%;margin-bottom:10px;" v-model:value="data.desc" size="large" placeholder="备注"/>


                <n-button type="primary" style="float:right" @click="on_save">
                  执行划扣
                </n-button>
              </n-card>
            </n-gi>
          </n-grid>
        </n-tab-pane>
      </n-tabs>
    </n-card>


    <n-drawer v-model:show="data.show_info" width="50%" placement="right">
      <Info :info-data="data.select_customer"/>
    </n-drawer>
    <n-drawer v-model:show="data.active"  :width="500">
      <n-drawer-content>
        <template #header>
          {{data.drawer_title}}
        </template>
        <n-tabs type="segment" animated size="large" :tabs-padding="0" pane-style="padding: 0px;" @before-leave="select_tab">
          <n-tab-pane name="必得组合"  style="min-height: 300px;padding-top: 20px" >
            <div v-for="item in data.todo_data['bd_include']" :key="item.id">
              <n-card :title="item.name+'—'+item.id" class="customer_card" @click="select_kx_projects(item)">
                <template #header-extra>
                  <NTag type="error">已选择</NTag>&nbsp;
                </template>
                <template #footer>
                  <n-flex style="margin-bottom: 5px" v-for="item2 in item.goods">
                    <n-tag type="primary">{{item2.goods_name}}-{{item2.sku_name}}</n-tag>
                    <n-tag type="error" v-if="item.type===1">{{item2.num}}次</n-tag>
                  </n-flex>
                  <n-alert type="warning" v-if="item.type===1">单次可用{{item.goods[0].num}}次</n-alert>
                  <n-alert type="warning" v-if="item.type===2">合计可用{{item.times}}次</n-alert>
                  <n-alert type="warning" v-if="item.type===3">时段{{item.times}}次</n-alert>
                </template>
              </n-card>
            </div>
          </n-tab-pane>
          <n-tab-pane name="自选组合"  style="min-height: 300px;padding-top: 20px">
            <div v-if="data.todo_data['zx_include']">
              <n-h5>自选组合——{{data.todo_data['zx_include'].length}}选{{data.todo_data['zx_can_do']}}</n-h5>

              <div v-for="item in data.todo_data['zx_include']" :key="item.id">

                <n-card :title="item.name+'—'+item.id" class="customer_card" @click="select_kx_projects(item)">
                  <template #header-extra>
                    <NTag type="success" v-if="item.is_select===false">未选择</NTag>&nbsp;
                    <NTag type="error" v-if="item.is_select===true">已选择</NTag>&nbsp;
                  </template>
                  <template #footer>
                    <n-flex style="margin-bottom: 5px" v-for="item2 in item.goods">
                      <n-tag type="primary">{{item2.goods_name}}-{{item2.sku_name}}</n-tag>
                      <n-tag type="error" v-if="item.type===1">{{item2.num}}次</n-tag>
                    </n-flex>
                    <n-alert type="warning" v-if="item.type===1">单次可用{{item.goods[0].num}}次</n-alert>
                    <n-alert type="warning" v-if="item.type===2">合计可用{{item.times}}次</n-alert>
                    <n-alert type="warning" v-if="item.type===3">时段{{item.times}}次</n-alert>
                  </template>
                </n-card>
              </div>
            </div>
          </n-tab-pane>
        </n-tabs>


        <template #footer>
          <n-button type="primary" @click="use_card">开卡</n-button>
        </template>
      </n-drawer-content>
    </n-drawer>
  </AppPage>

</template>


<style>
.customer_card{
  margin: 10px 0;
}
.other_card{
  margin: 10px 0;
}
</style>
